package github.sf.fw.tools.db.impl.nebula;


import github.sf.fw.tools.db.AbstractTableDataWriter;
import github.sf.fw.tools.db.DSConnector;
import github.sf.fw.tools.db.DSProperty;
import github.sf.fw.tools.db.connector.NebulaConnector;
import github.sf.fw.tools.db.model.ColumnInfo;
import github.sf.fw.tools.db.model.ResultData;
import github.sf.fw.tools.db.model.ResultRow;
import github.sf.fw.tools.db.model.TableInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class NebulaTableDataWriter extends AbstractTableDataWriter {


    public NebulaTableDataWriter(DSProperty dsProperty) {
        super(dsProperty);
    }

    @Override
    public int writer(TableInfo tableInfo, List<ResultRow> resultRowList) {
        NebulaConnector nebulaConnector = new NebulaConnector(dsProperty);
        writer(nebulaConnector, tableInfo, resultRowList);
        return 0;
    }

    @Override
    public void writer(DSConnector dsConnector, TableInfo tableInfo, List<ResultRow> resultRowList) {
        NebulaConnector nebulaConnector = (NebulaConnector) dsConnector;
        //处理映射关系
//        MappingJsonUtils.totranfer(tableInfo.getTableExtraInfo().getGraphInfo().getJson(), resultRowList);
        String grpthType = tableInfo.getTableExtraInfo().getGraphInfo().getGrpthType();
        //插入点
        if (grpthType.equalsIgnoreCase("tag")){
            String result="insert vertex %s(%s) values \"%s\"(%s)";
            String targetTableName = tableInfo.getTableExtraInfo().getTargetTableName();
            String releationKey="";
            String releationVaule="";
            String tagId="";
            int index = 0;
            StringBuilder key=new StringBuilder();
            StringBuilder value=new StringBuilder();
            try {
                int len = resultRowList.size();
                int offset = 0;
                while (index < len) {
                    for (int i = 0; i < 10000; i++) {
                        if (index == len) {
                            break;
                        }
                        ResultRow resultRow = resultRowList.get(index);
                        for (int i1 = 0; i1 < resultRow.size(); i1++) {
                            ResultData data = resultRow.get(i1);
                            if (i1==0){
                                tagId=data.getColumnValue().toString();
                            }
                            key.append(data.getColumnName()).append(",");
                            value.append("\"").append(data.getColumnValue()).append("\"").append(",");
                        }
                        releationKey=key.deleteCharAt(key.length()-1).toString();
                        releationVaule=value.deleteCharAt(value.length()-1).toString();
                        key.setLength(0);
                        value.setLength(0);
                        String format = String.format(result, targetTableName, releationKey, tagId, releationVaule);
                        nebulaConnector.dowrite(format);
                        index++;
                    }
                    offset++;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        //插入边信息
        else if (grpthType.equalsIgnoreCase("edge")) {
            // insert edge serve(startId,endId) values "181314024706908160" -> "123123123123":(181314024706908160,123123123123);
            String result="insert edge %s(%s) values \"%s\" ->\"%s\":(%s)";
            int len = resultRowList.size();
            int index = 0;
            int offset=0;
            String edgeFromId="";
            String edgeToId="";
            String relationKey="";
            String relationValue="";
            String targetTableName = tableInfo.getTableExtraInfo().getTargetTableName();
            //遍历数据 就是每一行的数据
            while (index < len) {
                StringBuilder stringKey=new StringBuilder();
                StringBuilder stringValue=new StringBuilder();
                for (int i = 0; i < 10000; i++) {
                    if (index == len) {
                        break;
                    }
                    ResultRow resultRow = resultRowList.get(index);
                    for (int i1 = 0; i1 < resultRow.size(); i1++) {
                        ResultData resultData = resultRow.get(i1);
                        if (resultData.getColumnName().equalsIgnoreCase("from")){
                            edgeFromId=resultData.getColumnValue().toString();
                        }else if (resultData.getColumnName().equalsIgnoreCase("to")){
                            edgeToId=resultData.getColumnValue().toString();
                        }
                        else {
                            stringKey.append(resultData.getColumnName()).append(",");
                            stringValue.append(resultData.getColumnValue()).append(",");
                        }
                    }
                    relationKey=stringKey.deleteCharAt(stringKey.length()-1).toString();
                    stringKey.setLength(0);
                    relationValue=stringValue.deleteCharAt(stringValue.length()-1).toString();
                    stringValue.setLength(0);
                    String format=String.format(result,targetTableName,relationKey,edgeFromId,edgeToId,relationValue);
                    //这里插入数据
                    nebulaConnector.dowrite(format);
                    index++;
                }
                offset++;
            }

        }
    }

    /**
     * 创建建表的语句
     * @param tableInfo
     * @param tableName
     * @return
     */
    public String createDDL(TableInfo tableInfo,String tableName ){
        String grpthType = tableInfo.getTableExtraInfo().getGraphInfo().getGrpthType();
        if (StringUtils.isBlank(grpthType)){
            throw new IllegalArgumentException("没有指定图的类型?点或边");
        }
        List<ColumnInfo> columnInfoList = tableInfo.getColumnInfoList();
        if (CollectionUtils.isEmpty(columnInfoList)) {
            throw new IllegalArgumentException("列信息为空，不能生成表创建语句:" + tableName);
        }
        //生成点的创建语句 CREATE TAG tang(name string, age int);
        //生成边的创建语句为 create edge tang(name Strng ,age int );
        String result="create %s %s%s;";
        String two="";
        StringBuilder stringBuilder=new StringBuilder("(");
        for (ColumnInfo columnInfo : columnInfoList){
            //String columnType = pureColumnType(columnInfo.getType());
            stringBuilder.append(columnInfo.getName()).append(" String").append(",");
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1).append(")");
        two=stringBuilder.toString();
        stringBuilder.setLength(0);
        return String.format(result,grpthType,tableName,two);
    }

    /**
     * 执行建表的语法
     * @param ddl
     * @return
     */
    protected boolean executeDDL(String ddl) {
        NebulaConnector nebulaConnector = new NebulaConnector(dsProperty);
        try {
            nebulaConnector.dowrite(ddl);
        }catch (Exception e){
         throw new RuntimeException("执行建表语句出错");
        }
        return true;
    }

    @Override
    public void deleteData(TableInfo tableInfo) {
    }

    @Override
    public void deleteTable(TableInfo tableInfo) {
    }

    @Override
    public void doUpdate(String script, Object[] args) {
    }
}
